﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public class RaceLogic : MonoBehaviour
{
    [DllImport("recast")]
    static extern IntPtr AllocRaceLogic();
    [DllImport("recast")]
    static extern void FreeRaceLogic(IntPtr handle);
    [DllImport("recast")]
    static extern void UpdateRaceLogic(IntPtr handle,long dt);
    [DllImport("recast")]
    static extern bool LoadGeomForRace(IntPtr ptr,byte[] buf, int length);
    [DllImport("recast")]
    static extern bool LoadGeomSettingForRace(IntPtr ptr, byte[] buf, int length);
    [DllImport("recast")]
    static extern bool LoadNavMeshForRace(IntPtr ptr, byte[] buf, int length);

    [SerializeField]
    TextAsset mesh_asset = null;
    [SerializeField]
    TextAsset geom_setting_asset = null;
    [SerializeField]
    TextAsset nav_mesh_asset = null;

    IntPtr mHandle = IntPtr.Zero;
    bool mInitialized = false;
    private void Awake()
    {
        UnityEngine.Debug.Log($"<color=#00ff00>RaceLogic Awake</color>");
        if (!InitMesh())
            return;
        UnityEngine.Debug.Log($"<color=#00ff00>初始化网格数据成功</color>");
        mInitialized = true;
    }

    public IntPtr Handle()
    {
        if (!mInitialized)
            return IntPtr.Zero;
        return mHandle;
    }

    bool InitMesh()
    {
        mHandle = AllocRaceLogic();
        if (IntPtr.Zero == mHandle)
            return false;
        if (null == mesh_asset || null == geom_setting_asset || null == nav_mesh_asset)
            return false;
        if (!LoadGeomForRace(mHandle, mesh_asset.bytes, mesh_asset.bytes.Length))
            return false;
        if (!LoadGeomSettingForRace(mHandle, geom_setting_asset.bytes, geom_setting_asset.bytes.Length))
            return false;
        if (!LoadNavMeshForRace(mHandle, nav_mesh_asset.bytes, nav_mesh_asset.bytes.Length))
            return false;
        return true;
    }

    private void Update()
    {
        UpdateRaceLogic(mHandle,0);
    }

    private void OnDestroy()
    {
        if(mHandle != IntPtr.Zero)
        {
            FreeRaceLogic(mHandle);
            mHandle = IntPtr.Zero;
        }
    }
}